package com.xuxu.topic;

import com.rabbitmq.client.*;
import com.xuxu.util.RabbitConnectionUtil;

import java.io.IOException;

/**
 * 通配符模式消费者 TOPIC
 */
public class Consumer1 {
    //定义交换机名称，要和生产者一样
    static final String TOPIC_EXCHANGE = "topic_exchange";
    //定义队列名称
    static final String TOPIC_QUEUE_1 = "topic_queue_1";

    public static void main(String[] args) throws Exception {
        //获取连接对象
        Connection connection = RabbitConnectionUtil.getConnection();
        //获取频道对象
        Channel channel = connection.createChannel();

        //声明交换机
        channel.exchangeDeclare(TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC);
        //声明队列
        channel.queueDeclare(TOPIC_QUEUE_1,true,false,false,null);
        //队列绑定交换机
        channel.queueBind(TOPIC_QUEUE_1,TOPIC_EXCHANGE,"topic.insert");

        //创建消费者对象
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //获取消息id
                System.out.println("消息id是：------   "+envelope.getDeliveryTag());

                //获取路由key
                System.out.println("路由key是：------   "+envelope.getRoutingKey());

                //获取交换机
                System.out.println("交换机是：------   "+envelope.getExchange());
            }
        };

        //持续监听，不需要关闭资源
        channel.basicConsume(TOPIC_QUEUE_1,true,consumer);

    }
}
